package com.hengda.museumonline.adapter;

import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hengda.museumonline.R;
import com.hengda.museumonline.view.EngineeringRecyclerView;

import java.util.List;

/**
 * Created by RaphetS on 2016/10/1.
 * 支持上拉加载
 * 底部有进度条
 */

public abstract class BaseLoadMoreHeaderAdapter<T> extends RecyclerView.Adapter {
    private Context mContext;
    private boolean isLoading = true;
    private OnLoadMoreListener mOnLoadMoreListener;
    private List<T> mDatas;
    private int mLayoutId;
    private View mHeadView;
    private final static int TYPE_HEADVIEW = 100;
    private final static int TYPE_ITEM = 101;
    private final static int TYPE_PROGRESS = 102;
    private final static int TYPE_PROGRESS2 = 103;
    private ProgressViewHolder progressViewHolder;
    private int downY;
    private final int DOWN_PULL = 0;    // 头布局状态: 下拉刷新
    private final int RELEASE_REFRESH = 1;    // 头布局状态:　释放刷新
    private final int REFRESHING = 2;    // 头布局状态:　正在刷新中..
    private int currentState = DOWN_PULL;
    private int headerViewHeight;
    private OnRefreshListener mOnRefreshListener;
    private TextView tvState;

    public BaseLoadMoreHeaderAdapter(Context mContext, RecyclerView recyclerView, List<T> mDatas, int mLayoutId) {
        this.mContext = mContext;
        this.mDatas = mDatas;
        this.mLayoutId = mLayoutId;
        init(recyclerView);
    }

    private void init(final RecyclerView recyclerView) {
        //mRecyclerView添加滑动事件监听
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int totalItemCount = linearLayoutManager.getItemCount();
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                if (isLoading && dy > 0 && lastVisibleItemPosition >= totalItemCount - 1) {
                    //此时是刷新状态
                    if (mOnLoadMoreListener != null) {
                        mOnLoadMoreListener.onLoadMore();
                    }
                }
            }
        });
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent ev) {
                if (mHeadView != null) {
                    switch (ev.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            downY = (int) ev.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            // 当前的状态是否是正在刷新中, 如果是, 直接跳出.
                            if (currentState == REFRESHING) {
                                break;
                            }

                            int moveY = (int) ev.getY();

                            // 间距 = 移动y - 按下y;
                            int diffY = moveY - downY;
                            System.out.println("diffY:" + diffY);
                            // 计算头布局最新的paddingTop = -头布局高度 + 间距.
                            int paddingTop = -headerViewHeight + 1 + diffY / 3;
                            //   System.out.println("diffY: " + diffY + ",downY:" + downY + ",moveY:" + moveY);

                            // 如果paddingTop的值 < -headerViewHeight, 不进行下拉刷新头的滑动操作.
                            // 并且ListView顶部第一个显示的条目的索引为: 0, 才可以进行滑动.

                            // 获取ListView顶部第一个显示的条目的索引
                            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                            int firstVisiblePosition = linearLayoutManager.findFirstVisibleItemPosition();
//                            System.out.println("firstVisiblePosition: " + firstVisiblePosition);
                            if (paddingTop > -headerViewHeight + 1 && firstVisiblePosition == 0) {
                                if (paddingTop > 0 && currentState == DOWN_PULL) { // 头布局完全显示, 并且当前状态是下拉刷新, 进入到松开刷新的状态
//                                    System.out.println("松开刷新");
                                    currentState = RELEASE_REFRESH;
                                    refreshHeaderViewState();
                                } else if (paddingTop < 0 && currentState == RELEASE_REFRESH) { // 头布局没有完全显示, 并且当前状态是松开刷新, 进入到下拉刷新的状态
//                                    System.out.println("下拉刷新");
                                    currentState = DOWN_PULL;
                                    refreshHeaderViewState();
                                }
                                mHeadView.setPadding(0, paddingTop, 0, 0);
                                return true; // 自己处理用户触摸滑动的事件.
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            // 判断当前的状态是哪一种
                            if (currentState == DOWN_PULL) { // 当前是在下拉刷新状态下松开了, 什么都不做, 把头布局隐藏就可以.
                                mHeadView.setPadding(0, -headerViewHeight + 1, 0, 0);
                            } else if (currentState == RELEASE_REFRESH) { // 当前的状态属于释放刷新, 并且松开了. 应该把头布局正常显示, 进入正在刷新中状态.
                                mHeadView.setPadding(0, 0, 0, 0);
                                currentState = REFRESHING;
                                refreshHeaderViewState();

                                // 调用用户的监听事件.
                                if (mOnRefreshListener != null) {
                                    mOnRefreshListener.onPullDownRefresh();
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
                return false;
            }
        });
    }

    /**
     * 根据当前的状态currentState来刷新头布局的状态.
     */
    private void refreshHeaderViewState() {
        switch (currentState) {
            case DOWN_PULL:     // 下拉刷新
                //   ivArrow.startAnimation(downAnimation);
                tvState.setText("下拉刷新");
                break;
            case RELEASE_REFRESH: // 松开刷新
//                ivArrow.startAnimation(upAnimation);
                tvState.setText("松开刷新");
                break;
            case REFRESHING: // 正在刷新中
//                ivArrow.clearAnimation(); // 把自己身上的动画清除掉
//                ivArrow.setVisibility(View.INVISIBLE);
//                mProgressBar.setVisibility(View.VISIBLE);
                tvState.setText("正在刷新..");
                break;
            default:
                break;
        }
    }

    /**
     * 刷新完成, 用户调用此方法, 把对应的头布局或脚布局给隐藏掉
     */
    public void onRefreshFinish() {

        mHeadView.setPadding(0, -headerViewHeight + 1, 0, 0);
        currentState = DOWN_PULL;
        tvState.setText("下拉刷新");
    }

    public void updateData(List<T> data) {
        mDatas.clear();
        mDatas.addAll(data);
        notifyDataSetChanged();
    }

    public void addAll(List<T> data) {
        mDatas.addAll(data);
        notifyDataSetChanged();
    }

    public void addHeadView(View headView) {
        tvState = (TextView) headView.findViewById(R.id.tv_listview_header_state);
        headView.measure(0, 0);    // 让系统框架去帮我们测量头布局的宽和高.
        // 获得一个测量后的高度, 只有在measure方法被调用完毕后才可以得到具体高度.
        headerViewHeight = headView.getMeasuredHeight();
        headView.setPadding(0, -headerViewHeight + 1, 0, 0);
        mHeadView = headView;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View itemView = LayoutInflater.from(mContext).inflate(mLayoutId, parent, false);
            BaseViewHolder baseViewHolder = new BaseViewHolder(itemView);
            return baseViewHolder;
        } else if (viewType == TYPE_HEADVIEW) {
            HeadViewHolder headViewHolder = new HeadViewHolder(mHeadView);
            return headViewHolder;
        } else if (viewType == TYPE_PROGRESS) {
            View progressView = LayoutInflater.from(mContext).inflate(R.layout.progress_item, parent, false);
            ImageView imageView = (ImageView) progressView.findViewById(R.id.iv_logo);
            Glide.with(mContext).load(R.drawable.logo).asGif().into(imageView);
            progressViewHolder = new ProgressViewHolder(progressView);
            return progressViewHolder;
        } else {
            TextView textView = new TextView(mContext);
            textView.setText("");
            progressViewHolder = new ProgressViewHolder(textView);
            return progressViewHolder;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof BaseViewHolder) {
            if (mHeadView != null) {
                if (position > 0) {
                    convert(mContext, holder, mDatas.get(position - 1));
                }
            } else {
                convert(mContext, holder, mDatas.get(position));
            }

        }
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeadView != null) {
            if (position == getItemCount() - 1) {
                return TYPE_PROGRESS;
            } else if (position == 0) {
                return TYPE_HEADVIEW;
            } else {
                return TYPE_ITEM;
            }
        } else {
            if (position == getItemCount() - 1) {
                if (isLoading) {
                    return TYPE_PROGRESS;
                } else {
                    return TYPE_PROGRESS2;
                }

            } else {
                return TYPE_ITEM;
            }
        }
    }


    public abstract void convert(Context mContext, RecyclerView.ViewHolder holder, T t);

    @Override
    public int getItemCount() {
        if (mHeadView != null) {
            return mDatas.size() + 2;
        } else {
            return mDatas.size() + 1;
        }

    }

    public void setLoading(boolean b) {
        isLoading = b;
    }


    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        this.mOnLoadMoreListener = listener;
    }

    public interface OnLoadMoreListener {
        void onLoadMore();
    }

    public class ProgressViewHolder extends RecyclerView.ViewHolder {
        public ProgressViewHolder(View itemView) {
            super(itemView);
        }
    }

    public class HeadViewHolder extends RecyclerView.ViewHolder {
        public HeadViewHolder(View itemView) {
            super(itemView);
        }
    }

    public void setOnRefreshListener(OnRefreshListener listener) {
        mOnRefreshListener = listener;
    }

    public interface OnRefreshListener {

        void onPullDownRefresh();

    }
}
